<template>
  <Header></Header>
  <div
      style="width: 100%;display: flex;justify-content: center;background-color: rgba(247, 247, 247, 1);min-height: 100vh;padding-top: 60px;padding-bottom: 200px">
    <div style="width: 1200px">
      <!--        视频播放{{subject_id}}{{subject_name}}-->
      <div v-if="state == '1'">
        <div v-if="JSON.stringify(liveUrlList) != '{}'">
          <LivePlayer
              :vid="JSON.stringify(liveUrlList)"
              :wh_ratio="1920/1080">
          </LivePlayer>
        </div>
        <div v-else>
          <div class="default-bg">
            <img class="bg-image"
                 :src="liveStreamingMessage.bannerPicWeb ? liveStreamingMessage.bannerPicWeb:liveStreamingMessage.bannerPic"
                 alt="">
            <div class="zzc">
              <div class="zzc-message">直播还未开始，请稍后...</div>
            </div>
          </div>
        </div>
      </div>
      <div v-if="state == '2'">
        <div v-if="liveStreamingMessage.aliVid && liveStreamingMessage.playAuth">
          <Player
              v-if="state == '2'"
              @ready="onReady"
              :vid="liveStreamingMessage.aliVid"
              :play_auth="liveStreamingMessage.playAuth"
              ref="playerRef"
              @playing="videoPlay"
              @pause="videoPause"
              :wh_ratio="1920/1080">
          </Player>
        </div>
      </div>
      <div class="video-body">
        <el-row justify="space-between">
          <el-col :span="17">
            <el-breadcrumb :separator-icon="'ArrowRightBold'">
              <el-breadcrumb-item class="link" @click="$router.push({name:'index'})">首页</el-breadcrumb-item>
              <el-breadcrumb-item class="link" @click="toMyLive">我的直播</el-breadcrumb-item>
              <el-breadcrumb-item style="display:inline-block;width: 450px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">{{ liveStreamingMessage.title }}</el-breadcrumb-item>
            </el-breadcrumb>
            <div style="display: flex;justify-content: space-between;align-items: center;padding: 20px 0px">
              <span>{{ liveStreamingMessage.title }}</span>
<!--              <el-button type="primary">收藏</el-button>-->
            </div>
            <div>
              <el-tabs v-model="activeName" class="demo-tabs">
                <el-tab-pane v-if="state == '1'" label="聊天" name="chat">
                  <TenXunIm :videoGroupId="videoGroupId" @loadingVideo="loadingVideo"></TenXunIm>
                </el-tab-pane>
                <el-tab-pane label="简介" name="describe">
                  <el-card v-if="liveStreamingMessage.describe">
                    <div v-html="liveStreamingMessage.describe"></div>
                  </el-card>
                  <el-empty v-else description="暂无文件" />
                </el-tab-pane>
                <el-tab-pane label="文件" name="file">
                  <el-card v-if="files.length">

                    <p class="file" @click="lookFile(item.url)" v-for="item in files">
                      {{ item.name }}
                    </p>
                  </el-card>
                  <el-empty v-else description="暂无文件" />
                </el-tab-pane>
              </el-tabs>
            </div>
          </el-col>
          <el-col :span="6" v-if="liveStreamingMessage && liveStreamingMessage.admin">
            <el-card>
              <el-row>
                <el-col :span="24">
                  <div style="display: flex;align-items: center">
                    <el-avatar :size="50" :src="liveStreamingMessage.admin.avatarPic || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"/>
                    <div style="margin-left: 20px" @click="test">讲师：{{ liveStreamingMessage.admin.name }}</div>
                  </div>
                </el-col>
                <el-col :span="24">
                  <div>
                    <!--                                        {{data.location}}&#45;&#45;{{TotalSecondRef}}-->
                    <div style="font-size: 14px;margin-top: 10px" v-if="liveStreamingMessage.admin.describe">简介：{{ liveStreamingMessage.admin.describe }}</div>
                  </div>
                </el-col>
              </el-row>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
  <staticFooter></staticFooter>
</template>

<script>
import TenXunIm from '@/components/TenXunIm/index'
// import TIM from "tim-js-sdk";
import Header from "@/components/Header";
import staticFooter from "@/components/staticFooter";
import {set_bull_screen} from "../../components/Player/js/player_components";
import LivePlayer from "../../components/LivePlayer/Player";
import Player from "../../components/Player/Player";
import {reactive, toRefs, ref, watchEffect, getCurrentInstance, computed,onBeforeUnmount} from 'vue'
import {useRoute, useRouter} from "vue-router";
import {
  liveReserve,
  videoAuth,
  liveReserveMessage,
  newsletter,
  meImToken,
  newsletterToChatWith,
  liveReserveLogTime
} from "../../api/api";
import GenerateTestUserSig from "../../../debug/GenerateTestUserSig";

export default {
  name: "index",
  setup() {
    // const userID = 'user139370';
    // const {userSig} = GenerateTestUserSig(userID)
    // const internalInstance = getCurrentInstance();

    // let onMessageReceived = function(event) {
    //   // event.data - 存储 Message 对象的数组 - [Message]
    //   const messageList = event.data;
    //   console.log('messageList',messageList)
    //   messageList.forEach((message) => {
    //     if (message.type === TIM.TYPES.MSG_TEXT) {
    //       console.log('文本消息 - https://web.sdk.qcloud.com/im/doc/zh-cn/Message.html#.TextPayload')
    //     } else if (message.type === TIM.TYPES.MSG_IMAGE) {
    //       // 图片消息 - https://web.sdk.qcloud.com/im/doc/zh-cn/Message.html#.ImagePayload
    //     } else if (message.type === TIM.TYPES.MSG_SOUND) {
    //       // 音频消息 - https://web.sdk.qcloud.com/im/doc/zh-cn/Message.html#.AudioPayload
    //     } else if (message.type === TIM.TYPES.MSG_VIDEO) {
    //       // 视频消息 - https://web.sdk.qcloud.com/im/doc/zh-cn/Message.html#.VideoPayload
    //     } else if (message.type === TIM.TYPES.MSG_FILE) {
    //       // 文件消息 - https://web.sdk.qcloud.com/im/doc/zh-cn/Message.html#.FilePayload
    //     } else if (message.type === TIM.TYPES.MSG_CUSTOM) {
    //       // 自定义消息 - https://web.sdk.qcloud.com/im/doc/zh-cn/Message.html#.CustomPayload
    //     } else if (message.type === TIM.TYPES.MSG_MERGER) {
    //       // 合并消息 - https://web.sdk.qcloud.com/im/doc/zh-cn/Message.html#.MergerPayload
    //     } else if (message.type === TIM.TYPES.MSG_LOCATION) {
    //       // 地理位置消息 - https://web.sdk.qcloud.com/im/doc/zh-cn/Message.html#.LocationPayload
    //     } else if (message.type === TIM.TYPES.MSG_GRP_TIP) {
    //       // 群提示消息 - https://web.sdk.qcloud.com/im/doc/zh-cn/Message.html#.GroupTipPayload
    //     } else if (message.type === TIM.TYPES.MSG_GRP_SYS_NOTICE) {
    //       // 群系统通知 - https://web.sdk.qcloud.com/im/doc/zh-cn/Message.html#.GroupSystemNoticePayload
    //     }
    //   });
    // };
    // internalInstance.appContext.config.globalProperties.$tim.on(TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived);
    //
    // const timLogin = (userId, userSig) => {
    //   //注意，这里的userID必须为String类型，请自行转化
    //   console.log('internalInstance', internalInstance)
    //   let promise = internalInstance.appContext.config.globalProperties.$tim.login({
    //     userID: userID.toString(),
    //     userSig
    //   });
    //   promise
    //       .then((imResponse) => {
    //         // 登录成功
    //         console.log('登录成功!!!!!!!!!!!!!!!!')
    //         if (imResponse.data.repeatLogin === true) {
    //           // 标识账号已登录，本次登录操作为重复登录。v2.5.1 起支持
    //         }
    //       })
    //       .catch(function (imError) {
    //         console.warn("login error:", imError); // 登录失败的相关信息
    //       });
    // }
    // timLogin(userID, userSig);
    //
    // let onSdkReady = function(event) {
    //   let promise1 = internalInstance.appContext.config.globalProperties.$tim.joinGroup({ groupID: '26008041080Vi0163', type: TIM.TYPES.GRP_AVCHATROOM });
    //   promise1.then(function(imResponse) {
    //     switch (imResponse.data.status) {
    //       case TIM.TYPES.JOIN_STATUS_WAIT_APPROVAL: // 等待管理员同意
    //         break;
    //       case TIM.TYPES.JOIN_STATUS_SUCCESS: // 加群成功
    //         console.log('加群成功',imResponse.data.group); // 加入的群组资料
    //         // // 2. 发送消息
    //         internalInstance.appContext.config.globalProperties.$tim.sendMessage(message).then(function(imResponse) {
    //           // 发送成功
    //           console.log('发送成功',imResponse);
    //         }).catch(function(imError) {
    //           // 发送失败
    //           console.warn('sendMessage error:发送失败', imError);
    //         });
    //         break;
    //       case TIM.TYPES.JOIN_STATUS_ALREADY_IN_GROUP: // 已经在群中
    //         break;
    //       default:
    //         break;
    //     }
    //   }).catch(function(imError){
    //     console.warn('joinGroup error:', imError); // 申请加群失败的相关信息
    //   });
    //   // 发送文本消息，Web 端与小程序端相同
    //   // 1. 创建消息实例，接口返回的实例可以上屏
    //   let message = internalInstance.appContext.config.globalProperties.$tim.createTextMessage({
    //     to: '26008041080Vi0163',
    //     conversationType: TIM.TYPES.CONV_GROUP,
    //     // 消息优先级，用于群聊（v2.4.2起支持）。如果某个群的消息超过了频率限制，后台会优先下发高优先级的消息，详细请参考：https://cloud.tencent.com/document/product/269/3663#.E6.B6.88.E6.81.AF.E4.BC.98.E5.85.88.E7.BA.A7.E4.B8.8E.E9.A2.91.E7.8E.87.E6.8E.A7.E5.88.B6)
    //     // 支持的枚举值：TIM.TYPES.MSG_PRIORITY_HIGH, TIM.TYPES.MSG_PRIORITY_NORMAL（默认）, TIM.TYPES.MSG_PRIORITY_LOW, TIM.TYPES.MSG_PRIORITY_LOWEST
    //     priority: TIM.TYPES.MSG_PRIORITY_NORMAL,
    //     payload: {
    //       text: '测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试'
    //     }
    //   });
    //
    // };
    // internalInstance.appContext.config.globalProperties.$tim.on(TIM.EVENT.SDK_READY, onSdkReady);

    let files = ref([])

    let route = useRoute();
    let router = useRouter();
    let {state} = route.params;

    let activeName = computed(() => state == '1' ? 'chat':'describe')

    let liveStreamingMessage = ref({})

    let liveUrlList = ref({})

    let playerRef = ref(null)

    let videoGroupId = ref('')
    //直播详情
    let getLiveStreaming = () => {
      let params = {
        id: route.params.id,
        course: Number(localStorage.getItem('activeCourse'))
      }
      liveReserveMessage(params).then(res => {
        console.log('直播详情', res.data)
        videoGroupId.value = res.data.groupCode
        let params = {}
        for (let item of res.data.url) {
          if (item.includes('SD')) {
            params['SD'] = item
          }
          if (item.includes('HD')) {
            params['HD'] = item
          }
          if (item.includes('smooth')) {
            params['流畅'] = item
          }
        }
        files.value = res.data.files
        liveUrlList.value = params
        liveStreamingMessage.value = res.data
      })
    }
    getLiveStreaming();

    const loadingVideo = () =>{
      getLiveStreaming();
    }

    //会话列表
    let getNewsLetter = () => {
      newsletter().then(res => {
        console.log('会话列表', res)
      })
    }
    getNewsLetter();

    //开始播放
    let onReady = () => {

    }

    //暂停播放
    let videoPause = () => {

    }

    let toMyLive = () => {
      router.push({name: 'MoreBroadCast', params: {state: state}})
    }

    let lookFile = (url) => {
      const href = router.resolve({ //使用resolve
        name:'pdfContainer',    //这里是跳转页面的name
        params:{pdf:url}
      })
        window.open(href.href,"_blank")
    }

    //播放器播放中
    let videoPlay = () =>{
      clearInterval(timer.value);
      console.log('正在播放---',Math.random())
      createInterval()
    }
    let timer = ref(null);
    let TotalSecondRef = ref(0);
    let createInterval = () =>{
      if(state == '2'){
        timer.value = setInterval(() =>{
          // console.log(playerRef.value.player.getStatus())
          if(playerRef.value.player && playerRef.value.player.getStatus() == 'playing'){
            TotalSecondRef.value++;
          }else{
            // clearInterval(timer.value);
          }
        },1000)
      }
    }

    let videoTimerFun = () =>{
      if(state == '2'){
        console.log('player',liveStreamingMessage.value.id);
        console.log(playerRef.value.player.getCurrentTime());
        let params = {
          liveStreamingID:liveStreamingMessage.value.id,
          second:playerRef.value.player.getCurrentTime()
        }

        liveReserveLogTime(params).then(res =>{
          console.log('记录成功',res);
        })
        window.removeEventListener('beforeunload',() =>{

        });
      }
    }
    // e141687531aa4c5682143f842e1315cd
    // e141687531aa4c5682143f842e1315cd
    onBeforeUnmount(() =>{
      console.log('组件销毁-------')
      videoTimerFun();
      clearInterval(timer.value);
    })

    //
    window.addEventListener('beforeunload', videoTimerFun);

    return {
      loadingVideo,
      videoGroupId,
      lookFile,
      files,
      state,
      videoPause,
      onReady,
      videoPlay,
      toMyLive,
      activeName,
      liveStreamingMessage,
      liveUrlList,
      playerRef
    }
  },
  components: {
    Header,
    LivePlayer,
    Player,
    staticFooter,
    TenXunIm
  }
}
</script>

<style scoped>


.default-bg {
  width: 100%;
  height: calc(1200px * (1080 / 1920));
  background: #00a5ff;
  position: relative;
}

.bg-image {
  position: absolute;
  left: 0px;
  top: 0px;
  right: 0px;
  bottom: 0px;
  width: 100%;
  height: 100%;
}

.zzc {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(0, 0, 0, .5);
  position: relative;
}

.zzc-message {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  color: white;
  background: #00a5ff;
  padding: 10px 15px;
  border-radius: 10px;
}

.file, .link {
  font-size: 14px;
  color: #8c939d;
  cursor: pointer;
}

.file:hover {
  color: #00a5ff;
}

.link :hover {
  color: #00a5ff !important;
}

.course-item .time {
  font-size: 12px;
  color: rgba(153, 153, 153, 1);
}

.course-item {
  display: flex;
  align-items: center;
  line-height: 48px;
  background-color: rgba(217, 235, 255, 1);
  margin-bottom: 5px;
  border-radius: 5px;
}

.video-body {
  margin: 20px 0px;
  width: 1200px;
}
</style>
